/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Alerta.java
 *
 * Created on 24/09/2010, 10:40:39
 */

package Util;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import model.execucao.ProcAtivDao;
import model.sistema.Grupo;
import model.sistema.Usuario;

/**
 *
 * @author Administrador
 */
public class Alerta extends javax.swing.JFrame {

    /** Creates new form Alerta */
    public Alerta() {
        initComponents();
        PreencheTabela();
        jTable1.setAutoResizeMode(jTable1.AUTO_RESIZE_OFF);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setTitle("Novas Tarefas entraram em Atraso!");
        setResizable(false);
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentHidden(java.awt.event.ComponentEvent evt) {
                formComponentHidden(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-411)/2, (screenSize.height-333)/2, 411, 333);
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentHidden(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentHidden
            PreencheTabela();
    }//GEN-LAST:event_formComponentHidden

    public void PreencheTabela()
    {
        
        Usuario user = manipulaConexao.getUsuarioLogado();
        sql = "select  a.idtarefa as 'Id',a.status as 'Prazo', b.nome as 'Atividade', a.solicitante as 'Solicitante',a.dt_limite as 'Data Limite', c.nome as 'Processo',a.transicao as 'Tarefa'"+
                            " from transicao a inner join atividade b on a.idativ = b.idatividade"+
                            " inner join processo c on a.idproc = c.idprocesso"+
                            " where resp = 1 and idresp = "+user.getId()+
                            " and a.status = 1 and a.alerta = 0 ";

       ArrayList<Grupo> grupos = manipulaConexao.getGrupoLogado();
       for(int i = 0; i < grupos.size() ; i++)
                    {

                        sql = sql + " or resp = 0 and idresp = "+grupos.get(i).getId() + " and a.status = 1 and a.alerta = 0";

                        }
       sql = sql + " order by a.idtarefa asc";
       manipulaConexao.preenchetable(jTable1, sql);
       DateFormat dtformat = new SimpleDateFormat("yyyy-MM-dd");
       try{
            new ProcAtivDao().formataData(jTable1, dtformat,sql);
        }catch(Exception exc)
       {
            JOptionPane.showMessageDialog(null, exc.getMessage(),"Erro",JOptionPane.ERROR_MESSAGE);
        }
    }

    public void VerificaDados(){
        if(!FabricaConexoes.verificaConexao()) FabricaConexoes.getConexao();

        try {
            stm = FabricaConexoes.returnStatement(sql);
            rs = FabricaConexoes.returnResult(stm);
            int inicio = 0;
            String sql2 = "update transicao set alerta = 1 where ";
            PreparedStatement stm2;
            int conteudo = 0;
            while (rs.next()) {
                if(inicio == 0 )
                {
                    this.setVisible(true);
                    int i = rs.getInt("Id");
                    sql2 = sql2 + "idtarefa = "+ i;
                }else{
                int i = rs.getInt("Id");
                sql2 = sql2 + " or idtarefa = "+ i;
                }
                conteudo = 1;
                inicio = 1;
            }
           if(conteudo == 1)
           {
               stm2 = FabricaConexoes.returnStatement(sql2);
           stm2.execute();

           stm2.close();
            }
            FabricaConexoes.closeConnection();
        } catch (Exception exc) {
            JOptionPane.showMessageDialog(null,exc.getMessage(),"Erro",JOptionPane.ERROR_MESSAGE );
        }
    }

    public void AdicionaLinha()
    {
        //modelo.addRow(new Object[]{null,null});
        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        if(!FabricaConexoes.verificaConexao()) FabricaConexoes.getConexao();
        stm = FabricaConexoes.returnStatement(sql);
        rs = FabricaConexoes.returnResult(stm);
        Object[] objeto = new Object[7];
        try
        {
        while(rs.next())
        {
           objeto[0] = rs.getInt("Id");
           objeto[2] = rs.getString("Atividade");
           objeto[3] = rs.getString("Solicitante");
           objeto[4] = rs.getString("Data limite");
           objeto[5] = rs.getString("Processo");
           objeto[6] = rs.getInt("tarefa");
           int prazo = rs.getInt("prazo");
           if(prazo == 0)
           {
            objeto[1] = "NORMAL";
           }else if(prazo == 1)
           {
            objeto[1] = "ATRASADO";
           }else
           {
             objeto[1] = "FECHADO";
           }
           
           modelo.addRow(objeto);
           this.toFront();
        }
        }catch(Exception exc)
        {
            JOptionPane.showMessageDialog(null, exc.getMessage());
        }
        
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Alerta().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
    private PreparedStatement stm;
    private ResultSet rs;
    private String sql;
    private int alerta = 0;

    public int getAlerta() {
        return alerta;
    }

    public void setAlerta(int alerta) {
        this.alerta = alerta;
    }
}
